package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数
        dto.checkParam();
        IPage page = new Page(dto.getPage(),dto.getSize());
        //2.是否收藏
        LambdaQueryWrapper<WmMaterial>queryWrapper= new LambdaQueryWrapper<>();
        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            //数据库中的数据与页面数据对比
            queryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //3.按照用户查询   用户id存与线程容器当中
        queryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());
        //4.按照时间查询
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        page = page(page,queryWrapper);
        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile)  {

        //1.参数的判断
        if(multipartFile.getSize() ==0 && multipartFile ==null){
            //为空,返回参数无效信息
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传图片到minIO中
        //文件名自定义,不能重复
        String fileName = UUID.randomUUID().toString().replaceAll("-","");
        //解析上传图片格式
        String originalFilename = multipartFile.getOriginalFilename();
        //截取后缀
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;

        try {

            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传失败!");
        }

        //3.保存到数据库中
        WmMaterial wmMaterial =new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(fileId);
        //自定义常量类
        wmMaterial.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
        wmMaterial.setIsCollection(WemediaConstants.CANCEL_COLLECT_MATERIAL);

        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        this.save(wmMaterial);

        //4.返回结果
        return ResponseResult.okResult(wmMaterial);
    }
}
